﻿using System;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Security;
using System.Runtime.InteropServices;

namespace CAW.DAO
{
    public class Model
    {
        private string _email;
        private SecureString _password;


        public string Email
        {
            set
            {
                _email = value;
            }
        }

        public SecureString Password
        {
            set
            {
                _password = value;
            }
        }

        private string GetClearTextPassword()
        {
            //Harumphhhhhh
            IntPtr str = Marshal.SecureStringToGlobalAllocUnicode(_password);
            string result;
            try
            {
                result = Marshal.PtrToStringUni(str);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(str);
            }
            return result;
        }


        public int GetWaitingGamesCount()
        {
            WebRequest req = WebRequest.Create("http://www.chessatwork.com/myhome/myhome.php");
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            string formFields = String.Format("loginemail={0}&loginpassword={1}"
                                                    , HttpUtility.UrlEncode(_email)
                                                    , HttpUtility.UrlEncode(GetClearTextPassword()));
            byte[] buffer = Encoding.UTF8.GetBytes(formFields);

            Stream reqStream = req.GetRequestStream();
            try
            {
                reqStream.Write(buffer, 0, buffer.Length);
            }
            finally
            {
                reqStream.Dispose();
            }

            WebResponse resp = req.GetResponse();

            Stream respStream = resp.GetResponseStream();
            string responseBody;
            try
            {
                StreamReader reader = new StreamReader(respStream);
                responseBody = reader.ReadToEnd();
            }
            finally
            {
                respStream.Dispose();
            }

            Regex rex = new Regex(@"var nGamesWaiting = (?<waitingGames>\d+)");
            Match m = rex.Match(responseBody);

            int result = int.Parse(m.Groups["waitingGames"].Value);

            return result;
        }
    }
}
